package com.itheima.train.manager.order.handler.mq;

import com.alibaba.fastjson.JSON;
import com.itheima.train.manager.domain.Order;
import com.itheima.train.manager.domain.OrderHandler;
import com.itheima.train.manager.order.handler.controller.WebSocketServer;
import com.itheima.train.manager.order.handler.service.TbOrderService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

@Component
public class OrderHandlerConsumer {
    
    // 创建一个日志记录器对象
    private Logger LOGGER = LoggerFactory.getLogger(OrderHandlerConsumer.class);
    
    @Autowired
    private TbOrderService orderService;
    
    @Autowired
    private RabbitmqProducer rabbitmqProducer;
    
    @Autowired
    private WebSocketServer webSocketServer;
    
    @RabbitListener(queues = "syn_gen_order_queue")
    public void orderHandlerConsumer(String orderHandlerJsonInfo, Message message, Channel channel) {
        
        Order order = null;
        try {
            
            // 1、对数据进行解析操作
            OrderHandler orderHandler = JSON.parseObject(orderHandlerJsonInfo, OrderHandler.class);
            
            // 2. 调用service层的代码完成数据的保存操作
            Thread.sleep(20000);                // 模拟保存订单业务逻辑处理时间
            order = orderService.saveOrder(orderHandler.getOrder());
            LOGGER.info("【保存订单数据完成】 ----> " + orderHandlerJsonInfo);
            
            // 发送删除redis中的排队信息消息
            String messageBody = order.getTrainNum() + ":" + order.getTrainRidingDate() + ":" + order.getUserId();
            rabbitmqProducer.sendMessage(messageBody, "delete_sorted");
            
            // 完成订单信息的推送
            sendOrderInfo(order.getUserId(), true, String.valueOf(order.getId()));
            
            // 3. 进行手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("【保存订单数据失败】 ----> " + orderHandlerJsonInfo);
            
            // 完成订单信息的推送
            sendOrderInfo(order.getUserId(), false, String.valueOf(order.getId()));
            
        }
        
    }
    
    // 进行消息的推送
    public void sendOrderInfo(String userId, boolean result, String orderId) {
        HashMap<String, Object> resultHashMap = new HashMap<>();
        resultHashMap.put("result", result);
        resultHashMap.put("orderId", orderId);
        webSocketServer.sendMessageToUser(userId, JSON.toJSONString(resultHashMap));
    }
    
    @RabbitListener(queues = "order_timeout_dlx_queue")
    public void orderTime(String orderIdJson, Message message, Channel channel) {
        
        try {
            
            LOGGER.info("【获取到订单超时消息】 ----> " + orderIdJson);
            HashMap<String, Long> hashMap = JSON.parseObject(orderIdJson, HashMap.class);
            Long orderId = hashMap.get("orderId");
            
            // 查询数据库信息
            Order order = orderService.queryOrderById(orderId);
            if ("0".equals(order.getPayStatus())) {
                
                // 修改订单的有效状态为为无效
                order.setIsEffect("0");
                
                // 数据更新
                orderService.updateOrderById(order);
                
                // 发送订单回退库存消息到mq中
                rabbitmqProducer.sendMessage(JSON.toJSONString(order), "back_stock");
                LOGGER.info("【订单超时消息成功获取，回退库存消息发送成功】 ---> " + orderIdJson);
                
            }
            
            // 给出应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
